package com.dotstone.chipism.activity;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.ShareContentAdapter;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.ShareInfo;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.listener.UpdateDataListener;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.ShareManager;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.BlurBehind;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBlurCompleteListener;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ShareContentActivity extends BaseActivity {
	private TextView tv_statusBar_mian;
	private ListView mShareLv;
	private Button mAddB;
	private LinearLayout mBackL;
	private ShareContentAdapter mAdapter;
	private List<ShareInfo> shares;
	private NormalDialog mNormalDialog;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private SVProgressHUD mSvprogressBar;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.add_share_btn:
			BlurBehind.getInstance().execute(MainActivity.mainActivity, new OnBlurCompleteListener() {
				@Override
				public void onBlurComplete() {
					Intent intent = new Intent(ShareContentActivity.this, ShareEditActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
					startActivity(intent);
					finish();
				}
			});
			break;

		default:
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				initData();
				break;

			default:
				break;
			}
		}
	};

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// initData();
		getAllShare();
		SocketManager.getInstance().setOnUpdateDataListener(new UpdateDataListener() {

			@Override
			public void onUpdate() {
				// TODO Auto-generated method stub
				getAllShare();
			}
		});
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_share_content;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		BlurBehind.getInstance()
				// .withAlpha(100)
				// // .withFilterColor(Color.parseColor("#000000"))
				.setBackground(this);
		tv_statusBar_mian = $(R.id.tv_statusBar_mian);
		mBackL = $(R.id.back_layout);
		mShareLv = $(R.id.share_content_lv);
		mAddB = $(R.id.add_share_btn);
		boolVersion();
		mBackL.setOnClickListener(this);
		mAddB.setOnClickListener(this);
		mShareLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
				// TODO Auto-generated method stub
				BlurBehind.getInstance().execute(MainActivity.mainActivity, new OnBlurCompleteListener() {
					@Override
					public void onBlurComplete() {
						Intent intent = new Intent(getApplicationContext(), QrcodeActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
						intent.putExtra("entry", 2);
						intent.putExtra("shareInfoId", shares.get(position).getShareInfoId());
						intent.putExtra("shareInfoUserId", shares.get(position).getUserId());
						startActivity(intent);
					}
				});
			}
		});
		mShareLv.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
				// TODO Auto-generated method stub
				mNormalDialog = new NormalDialog(ShareContentActivity.this);
				mNormalDialog.content("是否删除该分享：" + shares.get(position).getShareName() + "？")
						.style(NormalDialog.STYLE_TWO)//
						.titleTextSize(18)//
						.showAnim(bas_in)//
						.dismissAnim(bas_out)//
						.show();
				mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
					@Override
					public void onBtnClick() {
						mNormalDialog.dismiss();
					}
				}, new OnBtnClickL() {
					@Override
					public void onBtnClick() {
						mNormalDialog.dismiss();
						mSvprogressBar = new SVProgressHUD(ShareContentActivity.this);
						mSvprogressBar.showWithStatus("正在删除");
						deleteShare(position);
					}
				});
				return true;
			}
		});
	}

	private void deleteShare(int position) {
		if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
			ToastShow.Show(getApplicationContext(), "没有网络");
			if (mSvprogressBar.isShowing()) {
				mSvprogressBar.dismiss();
			}
			return;
		}
		RequestParams params = new RequestParams(HttpURL.HANDLE_SHARE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("handelType", 9);
			obj.put("shareInfoId", shares.get(position).getShareInfoId());
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("userId", SocketManager.getInstance().user_id);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.d("Tag", "delete share " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("test", "delete =" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String resultCode = jsonObject.getString("resultCode");
					if (resultCode.equals("1")) {
						if (mSvprogressBar.isShowing()) {
							mSvprogressBar.dismiss();
						}
						ToastShow.Show(getApplicationContext(), "删除成功");
						getAllShare();
					} else {
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
					ToastShow.Show(getApplicationContext(), "删除失败，请稍后再试");
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}
		});
	}

	private void initData() {
		// shares = ShareManager.getInstance().getmShares();
		switch (ShareManager.getInstance().getShareType()) {
		case 1:
			shares = ShareManager.getInstance().getFamillyShares();
			break;
		case 2:
			shares = ShareManager.getInstance().getFriendShares();
			break;
		default:
			break;
		}
		mAdapter = new ShareContentAdapter(getApplicationContext(), shares);
		mShareLv.setAdapter(mAdapter);
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			tv_statusBar_mian.setLayoutParams(layoutParams1);
			tv_statusBar_mian.setVisibility(View.VISIBLE);

		} else {
			tv_statusBar_mian.setVisibility(View.GONE);
		}
	}

	private void getAllShare() {
		RequestParams params = new RequestParams(HttpURL.GET_SHARE_INFO_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("Tag", result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						JSONArray ja = jo.getJSONArray("data");
						ShareManager.getInstance().clearShare();
						for (int i = 0; i < ja.length(); i++) {
							JSONObject shareInfo = ja.getJSONObject(i);
							String shareInfoId = shareInfo.getString("shoreInfoId");
							String userId = shareInfo.getString("userId");
							String shareName = shareInfo.getString("shoreName");
							String sceneIds = shareInfo.optString("sceneIds");
							String deviceIds = shareInfo.optString("deviceIds");
							int invalidHour = shareInfo.getInt("invalidHour");
							int status = shareInfo.getInt("status");
							int type = shareInfo.getInt("type");
							String hid = shareInfo.getString("hid");
							ShareInfo s = new ShareInfo(shareInfoId, userId, shareName, sceneIds, deviceIds,
									invalidHour, status, type, hid);
							ShareManager.getInstance().addShare(s);
						}
						Message msg = Message.obtain();
						msg.what = 0;
						mHandler.sendMessage(msg);
					} else {

					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

}
